import 'dart:io';

import 'package:chatgreat/bloc/account_bloc.dart';
import 'package:chatgreat/helper/ability.dart';
import 'package:chatgreat/helper/cache.dart';
import 'package:chatgreat/helper/env.dart';
import 'package:chatgreat/helper/helper.dart';
import 'package:chatgreat/helper/http.dart';
import 'package:chatgreat/helper/logger.dart';
import 'package:chatgreat/helper/platform.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/creative_island/gallery/components/line_indicator.dart';
import 'package:chatgreat/page/setting/account_security.dart';
import 'package:chatgreat/page/component/account_quota_card.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/invite_card.dart';
import 'package:chatgreat/page/component/item_selector_search.dart';
import 'package:chatgreat/page/component/sliver_component.dart';
import 'package:chatgreat/page/component/social_icon.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/page/component/theme/theme.dart';
import 'package:chatgreat/helper/constant.dart';
import 'package:chatgreat/page/component/dialog.dart';
import 'package:chatgreat/repo/api/user.dart';
import 'package:chatgreat/repo/api_server.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:clipboard/clipboard.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:quickalert/models/quickalert_type.dart';
import 'package:settings_ui/settings_ui.dart';
// import 'package:stripe_js/stripe_js.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../../helper/color.dart';
import '../../helper/event.dart';
import '../../helper/my_widget.dart';
import '../../helper/upload.dart';
import '../../repo/model/app_config.dart';
import '../login/model/tourist_login_model.dart';
import '../web/web_page.dart';

//我的
class SettingScreen extends StatefulWidget {
  final SettingRepository settings;
  const SettingScreen({super.key, required this.settings});

  @override
  State<SettingScreen> createState() => _SettingScreenState();
}

class _SettingScreenState extends State<SettingScreen>
    with SingleTickerProviderStateMixin {
  File? _avaterImageFile;
  AppConfig? emailConfig;
  AppConfig? phoneConfig;

  late TabController tabController;

  @override
  void initState() {
    tabController = TabController(length: 2, vsync: this);
    super.initState();

    context.read<AccountBloc>().add(AccountLoadEvent());
    context.read<AccountBloc>().add(AccountGetConfigEvent());

    GlobalEvent().on("refresh_4", (data) {
      if (mounted) {
        print('--------------> refresh_4');
        context.read<AccountBloc>().add(AccountLoadEvent());
        context.read<AccountBloc>().add(AccountGetConfigEvent());
      }
    });
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;

    return BackgroundContainer(
      setting: widget.settings,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child: Scaffold(
            backgroundColor: Colors.transparent,
            body: BlocConsumer<AccountBloc, AccountState>(
              listener: (context, state) {
                if (state is AccountConfig) {
                  if (state.config.key == 'email') {
                    emailConfig = state.config;
                  } else if (state.config.key == 'phone') {
                    phoneConfig = state.config;
                  }
                }
              },
              buildWhen: (previous, current) => current is AccountLoaded,
              builder: (context, state) {
                return _buildSettingsWidget(context, state);
              },
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSettingsWidget(context, AccountState accountState) {
    return CustomScrollView(
      slivers: [
        SliverToBoxAdapter(
            child: _buildAccountQuotaCard(context, accountState)),
        SliverToBoxAdapter(
            child: Wrap(
          direction: Axis.horizontal,
          alignment: WrapAlignment.start,
          // spacing: 8.0,
          runSpacing: 34.w,
          children: buildWrapItem(),
        ))
      ],
    );
  }

  CustomSettingsSection _buildAccountQuotaCard(
    BuildContext context,
    AccountState state,
  ) {
    TouristLoginModel? userInfo;
    if (state is AccountLoaded) {
      userInfo = state.user;
    }

    return CustomSettingsSection(
      child: AccountQuotaCard(
        avaterImageFile: _avaterImageFile,
        userInfo: userInfo,
        onPaymentReturn: () {
          if (userInfo != null) {
            context.read<AccountBloc>().add(AccountLoadEvent(cache: false));
          }
        },
        onChangeNameReturn: (text) {
          userInfo?.name = text;
          setState(() {});

          EasyLoading.show(status: '请稍等...');
          APIServer().updateUserInfo(name: text).then((value) {
            EasyLoading.dismiss();
          }).catchError((e) {
            EasyLoading.dismiss();
          });
        },
        onChangeAvaterReturn: () {
          openCustomComfirBottomSheet(
            context,
            (context) {
              return SizedBox(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    GestureDetector(
                      onTap: () async {
                        context.pop();
                        PermissionStatus status = await Permission.camera.status;
                        if (!status.isGranted) {
                          // 请求相册权限
                          status = await Permission.camera.request();
                          if (!status.isGranted) {
                            showJurisdictionDialog(context, 2);
                            return;
                          }
                        }

                        final pickedImage = await ImagePicker()
                            .pickImage(source: ImageSource.camera);
                        if (pickedImage != null) {
                          _avaterImageFile = File(pickedImage.path);
                          setState(() {});

                          EasyLoading.show(status: '请稍等...');
                          QiniuUploader(widget.settings)
                              .uploadFile(File(pickedImage.path))
                              .then((value) {
                            userInfo?.portrait = value.url;
                            APIServer()
                                .updateUserInfo(portrait: value.url)
                                .then((value) {
                              EasyLoading.dismiss();
                            }).catchError((e) {
                              EasyLoading.dismiss();
                            });
                          }).catchError((e) {
                            EasyLoading.dismiss();
                          });
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 55,
                        color: Colors.transparent,
                        child: MyTextWeight(
                            '拍照', 19, Colors.white, FontWeight.w500),
                      ),
                    ),
                    GestureDetector(
                      onTap: () async {
                        context.pop();

                        PermissionStatus status = await Permission.photos.status;
                        if (!status.isGranted) {
                          // 请求相册权限
                          status = await Permission.photos.request();
                          if (!status.isGranted) {
                            showJurisdictionDialog(context, 1);
                            return;
                          }
                        }

                        final pickedImage = await ImagePicker()
                            .pickImage(source: ImageSource.gallery);
                        if (pickedImage != null) {
                          _avaterImageFile = File(pickedImage.path);
                          setState(() {});

                          EasyLoading.show(status: '请稍等...');
                          QiniuUploader(widget.settings)
                              .uploadFile(File(pickedImage.path))
                              .then((value) {
                            userInfo?.portrait = value.url;
                            APIServer()
                                .updateUserInfo(portrait: value.url)
                                .then((value) {
                              EasyLoading.dismiss();
                            }).catchError((e) {
                              EasyLoading.dismiss();
                            });
                          }).catchError((e) {
                            EasyLoading.dismiss();
                          });
                        }
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 55,
                        color: Colors.transparent,
                        child: MyTextWeight(
                            '从手机相册选择', 19, Colors.white, FontWeight.w500),
                      ),
                    ),
                    Container(
                      color: const Color(0xFF252631).withOpacity(0.5),
                      height: 6,
                    ),
                    GestureDetector(
                      onTap: () {
                        context.pop();
                      },
                      child: Container(
                        alignment: Alignment.center,
                        height: 57,
                        color: Colors.transparent,
                        child: MyTextWeight(
                            '取消', 19, Colors.white, FontWeight.w500),
                      ),
                    ),
                  ],
                ),
              );
            },
            heightFactor: 0.8,
          );
        },
      ),
    );
  }

  CustomSettingsSection _buildInviteCard(
      BuildContext context, AccountLoaded state) {
    // !state.user!.showInviteMessage
    if (state.error != null) {
      return CustomSettingsSection(
        child: Container(),
      );
    }

    return CustomSettingsSection(
      child: Container(),
      // child: InviteCard(userInfo: state.user!),
    );
  }

  List<Widget> buildWrapItem() {
    var titles = ['清理缓存', '协议内容', '反馈问题', '联系我们', '注销账号', '退出登录'];
    var icons = [
      'huancun',
      'xieyi',
      'fankui',
      'lianxi',
      'zhuxiao',
      'exit_login'
    ];

    var itemWidth = (ScreenUtil().screenWidth - 13 * 2) / 4;
    List<Widget> list = [];
    for (int i = 0; i < titles.length; i++) {
      var title = titles[i];
      var icon = icons[i];

      list.add(GestureDetector(
        onTap: () => tapEvent(i),
        child: Container(
          width: itemWidth,
          padding: const EdgeInsets.only(top: 8, bottom: 8),
          color: Colors.transparent,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              imgWidget(23.w, 23.w, icon),
              SizedBox(height: 16.w),
              MyTextWeight(title, 13.w, Colors.white, FontWeight.normal)
            ],
          ),
        ),
      ));
    }
    return list;
  }

  void tapEvent(index) {
    if (index == 0) {
      // 清理缓存
      openConfirmDialog(
        context,
        AppLocale.confirmClearCache.getString(context),
        () async {
          await Cache().clearAll();
          await HttpClient.cacheManager.clearAll();
          showSuccessMessage(
            '清理完成',
          );
        },
        danger: true,
      );
    } else if (index == 1) {
      //协议内容
      //TODO: 协议内容
      showAgreementDialog(context, onSubmit: () {});
    } else if (index == 2) {
      //反馈问题
      context.push('/setting/feedback');
    } else if (index == 3) {
      //联系我们
      showAnimationDialog(
        context: context,
        transitionType: TransitionType.scale,
        barrierDismissible: true,
        builder: (context) => StatefulBuilder(builder: (context, state) {
          return Dialog(
            elevation: 0,
            backgroundColor: Colors.transparent,
            child: Container(
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(13),
                  color: stringToColor('FF333544')),
              constraints: BoxConstraints(
                maxHeight: ScreenUtil().screenHeight - 60,
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Stack(
                    children: [
                      Center(
                        child: Padding(
                          padding: const EdgeInsets.only(top: 20, bottom: 24),
                          child: MyTextWeight(
                              '联系我们', 18, Colors.white, FontWeight.normal),
                        ),
                      ),
                      Positioned(
                        right: 0,
                        top: 0,
                        child: IconButton(
                            padding: const EdgeInsets.all(16),
                            onPressed: () {
                              context.pop();
                            },
                            icon: const Icon(Icons.close)),
                      )
                    ],
                  ),
                  Padding(
                    padding: const EdgeInsets.only(top: 57, bottom: 38.5),
                    child: MyTextWeight('请通过以下方式联系我们以取得进展', 15,
                        Colors.white.withOpacity(0.6), FontWeight.w400),
                  ),
                  Visibility(
                    visible: phoneConfig != null && isNotBlank(phoneConfig!.value),
                    child: GestureDetector(
                      onTap: () {
                        context.pop();

                        var text = phoneConfig?.value ?? '';
                        FlutterClipboard.copy(text).then((value) {
                          showSuccessMessage('已复制到剪贴板');
                        });
                      },
                      child: Container(
                        color: Colors.transparent,
                        margin: const EdgeInsets.only(bottom: 12),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            MyTextWeight(phoneConfig?.value ?? '',
                                18, Colors.white, FontWeight.w400),
                            const SizedBox(width: 18),
                            imgWidget(15.5, 17, 'fuzhi'),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 60),
                    child: GestureDetector(
                      onTap: () {
                        context.pop();

                        var text = emailConfig?.value ?? '1054019490@163.com';
                        FlutterClipboard.copy(text).then((value) {
                          showSuccessMessage('已复制到剪贴板');
                        });
                      },
                      child: Container(
                        color: Colors.transparent,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            MyTextWeight(emailConfig?.value ?? '1054019490@163.com',
                                18, Colors.white, FontWeight.w400),
                            const SizedBox(width: 18),
                            imgWidget(15.5, 17, 'fuzhi'),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          );
        }),
      );
    } else if (index == 4) {
      //注销账号
      context.push('/setting/signout');
    } else if (index == 5) {
      showCustomTipsDialog(context, '退出登录', '退出当前账号无法清空历史记录',
          onSubmit: (diaContext) {
        diaContext.pop();

        context.read<AccountBloc>().add(AccountSignOutEvent());
        Future.delayed(const Duration(milliseconds: 450))
            .then((value) => context.go('/login'));
      });
    }
  }

  showAgreementDialog(BuildContext context,
      {required Function() onSubmit}) async {
    showAnimationDialog(
      context: context,
      transitionType: TransitionType.inFromTop,
      barrierDismissible: true,
      builder: (diaContext) => StatefulBuilder(builder: (diaContext, state) {
        return Dialog(
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            margin: const EdgeInsets.only(bottom: 50),
            width: 330,
            height: 478 + 52,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  width: 330,
                  height: 478,
                  decoration: BoxDecoration(
                    color: const Color(0xFF333544),
                    borderRadius: BorderRadius.circular(13),
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(13),
                    child: Column(
                      children: [
                        Container(
                          height: 44,
                          width: double.infinity,
                          margin: EdgeInsets.symmetric(horizontal: 65.w),
                          child: TabBar(
                            indicator: RoundUnderlineTabIndicator(
                                insets: const EdgeInsets.only(bottom: 2),
                                borderSide: BorderSide(
                                    width: 2.5.w,
                                    color: const Color(0xFF16DFEB))),
                            dividerColor: Colors.transparent,
                            labelColor: Colors.white,
                            labelStyle: const TextStyle(fontSize: 17),
                            labelPadding:
                                const EdgeInsets.only(left: 0, right: 0),
                            unselectedLabelColor: Colors.white.withOpacity(0.6),
                            unselectedLabelStyle: const TextStyle(fontSize: 16),
                            controller: tabController,
                            onTap: (index) {
                              // setState(() { });
                            },
                            tabs: const [
                              VgTab(text: '用户协议'),
                              VgTab(text: '隐私协议'),
                            ],
                          ),
                        ),
                        Expanded(
                          child: Container(
                            color: Colors.white,
                            child: TabBarView(
                              physics: const NeverScrollableScrollPhysics(),
                              controller: tabController,
                              children: [
                                WebViewPage(url: 'https://chatgreatgopro.captainfeng.fun//#/agreementInfo?id=1'),
                                WebViewPage(url: 'https://chatgreatgopro.captainfeng.fun//#/agreementInfo?id=2'),
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(left: 22, top: 22, right: 22),
                  child: InkWell(
                      onTap: () => diaContext.pop(),
                      child: imgWidget(30, 30, 'setting_close_icon')),
                )
              ],
            ),
          ),
        );
      }),
    );
  }

}

void showJurisdictionDialog(BuildContext context, int type) {
  showCupertinoDialog(
      context: context,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: const Text('提示'),
          content: Text(type == 1 ? '您未授权访问相册，无法使用保存相册功能，请在设置中允许访问照片/相册权限后重试' : '您未授权访问相机，无法使用拍照功能，请在设置中允许访问相机权限后重试'),
          actions: [
            CupertinoDialogAction(
              isDefaultAction: true,
              child: const Text(
                '取消',
                style: TextStyle(
                    color: Colors.white, fontWeight: FontWeight.normal),
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            CupertinoDialogAction(
              isDestructiveAction: true,
              child: const Text('去设置'),
              onPressed: () {
                context.pop();
                if (type == 1) {
                  launchUrlString('App-Prefs:Privacy&path=PHOTOS');
                } else {
                  launchUrlString('App-Prefs:Privacy&path=CAMERA');
                }
              },
            ),
          ],
          insetAnimationDuration: const Duration(seconds: 2),
        );
      });
}